package com.dianrui.moonfire.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.SPUtils;
import com.dianrui.moonfire.Constant;
import com.dianrui.moonfire.R;
import com.dianrui.moonfire.adapter.WalletAdapter;
import com.dianrui.moonfire.bean.WalletBean;
import com.dianrui.moonfire.util.EventBusConstants;
import com.dianrui.moonfire.util.JsonUtils;
import com.dianrui.moonfire.okhttp.XHttpRequest;
import com.dianrui.moonfire.util.NoDoubleClickUtils;
import com.dianrui.moonfire.util.StringUtils;
import com.dianrui.moonfire.util.ToastUtil;
import com.dianrui.moonfire.util.Url;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 我的钱包
 */
@SuppressWarnings("ALL")
public class MyWalletActivity extends BaseActivity {
    private String financeId;
    private String settingId;
    private String name, feebback;
    private int depositCount;
    private String type = "2";
    private int mPageIndex = 1;
    private List<WalletBean> mWalletBeanList = new ArrayList<>();
    private WalletAdapter mWalletAdapter;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.balance)
    TextView balances;
    @BindView(R.id.deposit)
    TextView deposit;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.btn_consume_click)
    Button btnConsume;
    @BindView(R.id.btn_recharge_click)
    Button btnRecharge;
    @BindView(R.id.btn_withdraws_click)
    Button btnWithDraws;
    @BindView(R.id.refund_failed_layout)
    LinearLayout refundFailedLayout;


    @Override
    public int getContentViewId() {
        return R.layout.activity_wallet;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        customInit(true);
        title.setText(getString(R.string.wallet_title));
        getBalance();
        getFinance(false);
        LinearLayoutManager layoutManager = new LinearLayoutManager(MyWalletActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(MyWalletActivity.this, LinearLayoutManager.VERTICAL));
        mWalletAdapter = new WalletAdapter(mWalletBeanList);
        recyclerView.setAdapter(mWalletAdapter);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getFinance(true);
                refreshLayout.finishRefresh();
            }
        });

        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPageIndex++;
                getFinance(false);
                refreshLayout.finishLoadMore();
            }
        });
    }

    @Override
    public void initData() {
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(String str) {
        if (TextUtils.equals(str, EventBusConstants.REFRESH_WALLET_LIST)) {
            getBalance();
            getFinance(true);

        }


    }

    //获取我的钱包的余额和押金
    public void getBalance() {
        JsonObject balanceJson = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString(Constant.MEMBER_ID))) {
            balanceJson.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        XHttpRequest.getInstance().postRequests(Url.BALANCE, balanceJson.toString(), new XHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        if (isFinishing()) {
                            return;
                        }
                        JSONObject jsonObject = new JSONObject(result);
                        if (null != jsonObject) {
                            if (Constant.DATASUCCESS.equals(jsonObject.optString("status"))) {
                                String data = JsonUtils.getJsonStr(result, "data");
                                if ((jsonObject.optJSONObject("data").has("balance"))) {
                                    balances.setText(JsonUtils.getJsonStr(data, "balance"));
                                }
                                Double deposits = jsonObject.optJSONObject("data").optDouble("deposit");
                                if (deposits > 0) {
                                    StringBuilder depositBuilder = new StringBuilder();
                                    depositBuilder.append(jsonObject.optJSONObject("data").optString("deposit")).append(getString(R.string.despoit_money_txt));
                                    deposit.setText(depositBuilder.toString());
                                    deposit.setTextColor(getResources().getColor(R.color.black));
                                } else {
                                    StringBuilder depositBuilder = new StringBuilder();
                                    depositBuilder.append(jsonObject.optJSONObject("data").optString("deposit")).append(getString(R.string.despoit_money_txt1));
                                    deposit.setText(depositBuilder.toString());
                                    deposit.setTextColor(getResources().getColor(R.color.black));
                                }
                                if (jsonObject.optJSONObject("data").optInt("finance_id") > 0) {
                                    refundFailedLayout.setVisibility(View.VISIBLE);
                                } else {
                                    refundFailedLayout.setVisibility(View.GONE);
                                }
                                settingId = jsonObject.optJSONObject("data").optString("setting_id");
                                financeId = jsonObject.optJSONObject("data").optString("finance_id");
                                name = jsonObject.optJSONObject("data").optString("name");
                                feebback = jsonObject.optJSONObject("data").optString("feedback");
                                depositCount = jsonObject.optJSONObject("data").optInt("deposit_count");
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //获取我的财务记录(消费和充值)
    private void getFinance(final boolean isRfresh) {
        if (isRfresh) {
            mPageIndex = 1;
        }
        JsonObject jsonObject = new JsonObject();
        if (!StringUtils.isEmpty(SPUtils.getInstance().getString("member_id"))) {
            jsonObject.addProperty("member_id", SPUtils.getInstance().getString("member_id"));
        }
        jsonObject.addProperty("type", type);
        jsonObject.addProperty("p", mPageIndex);
        XHttpRequest.getInstance().postRequests(Url.FINANCE, jsonObject.toString(), new XHttpRequest.XCallBack() {

            @Override
            public void onResponse(String result) {

                if (isRfresh) {
                    mWalletBeanList.clear();
                }
                if (!StringUtils.isEmpty(result)) {
                    try {
                        if (isFinishing()) {
                            return;
                        }
                        String status = JsonUtils.getJsonStr(result, Constant.STATUS);
                        if (Constant.DATASUCCESS.equals(status)) {
                            String data = JsonUtils.getJsonStr(result, "data");
                            if (!StringUtils.isEmpty(data)) {
                                List<WalletBean> list = JsonUtils.jsonStrToList(data, new TypeToken<ArrayList<WalletBean>>() {}.getType());
                                if (list != null && list.size() > 0) {
                                    mWalletBeanList.addAll(list);
                                    mWalletAdapter.setNewData(list);
                                    refreshLayout.finishRefresh();
                                }
                            }
                        } else {
                            ToastUtil.showToast(JsonUtils.getJsonStr(result, "message"));
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (mWalletBeanList.size() <= 0) {
                        mWalletAdapter.getData().clear();
                        mWalletAdapter.setEmptyView(LayoutInflater.from(MyWalletActivity.this).inflate(R.layout.empty_view, null));
                        mWalletAdapter.notifyDataSetChanged();
                    } else {
                        recyclerView.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void failedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }


    @OnClick({R.id.back, R.id.btn_consume_click, R.id.balance_withdraw_btn, R.id.btn_recharge_click, R.id.recharge_btn, R.id.btn_withdraws_click, R.id.withdraws, R.id.withdraw_failed_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.withdraw_failed_btn:
                startActivity(new Intent(MyWalletActivity.this, WithDrawFailedSubmitActivity.class).putExtra("financeId", financeId).putExtra("name", name).putExtra("feedback", feebback));
                break;
            case R.id.btn_consume_click:
                btnConsume.setBackgroundResource(R.drawable.wallet_list_btn);
                btnConsume.setTextColor(getResources().getColor(R.color.black));

                btnRecharge.setTextColor(getResources().getColor(R.color.nav_color_txt));
                btnRecharge.setBackgroundColor(Color.TRANSPARENT);

                btnWithDraws.setTextColor(getResources().getColor(R.color.nav_color_txt));
                btnWithDraws.setBackgroundColor(Color.TRANSPARENT);

                type = "2";
                getFinance(true);
                break;
            case R.id.btn_recharge_click:
                btnConsume.setTextColor(getResources().getColor(R.color.nav_color_txt));
                btnConsume.setBackgroundColor(Color.TRANSPARENT);

                btnRecharge.setBackgroundResource(R.drawable.wallet_list_btn);
                btnRecharge.setTextColor(getResources().getColor(R.color.black));

                btnWithDraws.setTextColor(getResources().getColor(R.color.nav_color_txt));
                btnWithDraws.setBackgroundColor(Color.TRANSPARENT);

                type = "1";
                getFinance(true);
                break;
            case R.id.btn_withdraws_click:
                btnConsume.setTextColor(getResources().getColor(R.color.nav_color_txt));
                btnConsume.setBackgroundColor(Color.TRANSPARENT);

                btnRecharge.setTextColor(getResources().getColor(R.color.nav_color_txt));
                btnRecharge.setBackgroundColor(Color.TRANSPARENT);

                btnWithDraws.setBackground(getResources().getDrawable(R.drawable.wallet_list_btn));
                btnWithDraws.setTextColor(getResources().getColor(R.color.black));

                type = "3";
                getFinance(true);
                break;
            case R.id.recharge_btn:
                JumpActivitys(RechargeActivity.class);
                break;
            case R.id.withdraws:
                if (StringUtils.isEmpty(SPUtils.getInstance().getString("card"))) {
                    Intent intent = new Intent(MyWalletActivity.this, AuthActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("isBackAuth", "1");
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else if ("0.00".contains(deposit.getText().toString().replace("元,缴纳押金", ""))) {
                    Intent intent = new Intent(MyWalletActivity.this, DepositActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("isDespoitBack", "1");
                    bundle.putString("isborrowCar", "0");
                    intent.putExtras(bundle);
                    startActivity(intent);
                } else {
                    chooseArea();

                }
                break;


            default:
                break;
        }
    }

    //跳转选择区域
    private void chooseArea() {
        Intent intent = new Intent(MyWalletActivity.this, ChooseAddressListActivity.class);
        startActivity(intent);
        finish();
    }

    //跳转退款成功界面
    private void refund() {
        Intent intent = new Intent(MyWalletActivity.this, RefundDespotiSuccessActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("money", deposit.getText().toString());
        bundle.putString("settingid", settingId);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
